package org.xxpay.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.xxpay.core.entity.*;
import org.xxpay.core.service.ISysQuotaService;
import org.xxpay.service.dao.mapper.SysConfigMapper;
import org.xxpay.service.dao.mapper.SysQuotaMapper;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service(interfaceName = "org.xxpay.core.service.ISysQuotaService", version = "1.0.0", retries = -1)
public class ISysQuotaServiceImpl implements ISysQuotaService {

    @Autowired
    private SysQuotaMapper sysQuotaMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;


    @Override
    public List<SysQuota> select(int offset, int limit,SysQuota sysQuota) {
        SysQuotaExample example = new SysQuotaExample();
        example.setOrderByClause("createTime DESC");
        example.setOffset(offset);
        example.setLimit(limit);

        SysQuotaExample.Criteria criteria = example.createCriteria();
        if(sysQuota == null){
            return sysQuotaMapper.selectByExample(example);

        }
        if(sysQuota.getStartTime() != null && sysQuota.getEndTime() != null){
            criteria.andCreateTimeBetween(sysQuota.getStartTime(),sysQuota.getEndTime());
        }
        if(sysQuota.getUser_id() != null){
            criteria.andUser_idEqualTo(sysQuota.getUser_id());
        }

        return sysQuotaMapper.selectByExample(example);
    }

    @Override
    public Double getAmountCount() {
        SysConfig config = sysConfigMapper.selectByPrimaryKey("quota");
        return Double.valueOf(config.getValue());
    }


    @Override
    public int add(SysQuota sysQuota) {

        String amount = sysQuota.getAmount().toString();
        BigDecimal bigDecimal = new BigDecimal(amount);
        //计算总额度
        SysConfig config = sysConfigMapper.selectByPrimaryKey("quota");
        sysQuota.setPreChargePoint(Double.valueOf(config.getValue()));
        BigDecimal count = new BigDecimal(config.getValue()).add(bigDecimal);
        //更新
        config.setValue(count.toString());
        sysConfigMapper.updateByPrimaryKey(config);

        sysQuota.setPostChargePoint(Double.valueOf(count.toString()));
        sysQuota.setCreateTime(new Date());
        return sysQuotaMapper.insertSelective(sysQuota);
    }

    @Override
    public int delete() {
        SysConfig config = sysConfigMapper.selectByPrimaryKey("quota");
        config.setValue("0");
        return sysConfigMapper.updateByPrimaryKey(config);
    }

    @Override
    public int count() {
        return sysQuotaMapper.selectByExample(null).size();
    }
}
